//
//  SSEmoticonToolbar.swift
//  表情键盘
//
//  Created by 叶竞泽 on 2017/2/9.
//  Copyright © 2017年 叶竞泽. All rights reserved.
//

import UIKit

/// 表情键盘底部工具栏
class SSEmoticonToolbar: UIView {

    override func awakeFromNib() {
        
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        setupUI()
    }
}

fileprivate extension SSEmoticonToolbar {
    
    func setupUI() {
        
        // 设置按钮
        let manager = SSEmoticonManager.shared
        
        for (i, package) in manager.packages.enumerated() {
            guard let groupName = package.groupName else {
                continue
            }
            
            // 1.实例化按钮
            let button = UIButton()
            
            // 2.设置按钮状态
            button.setTitle(groupName, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            button.setTitleColor(UIColor.white, for: .normal)
            button.setTitleColor(UIColor.darkGray, for: .highlighted)
            button.setTitleColor(UIColor.darkGray, for: .selected)
            button.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
            
            let normalImageName = "compose_emotion_table_\(package.bgImageName ?? "")_normal"
            let selectedImageName = "compose_emotion_table_\(package.bgImageName ?? "")_selected"
            var normalImage = UIImage(named: normalImageName, in: manager.bundle, compatibleWith: nil)
            var selectedImage = UIImage(named: selectedImageName, in: manager.bundle, compatibleWith: nil)
            
            let size = normalImage?.size ?? CGSize()
            let inset = UIEdgeInsets(top: size.height * 0.5, left: size.width * 0.5, bottom: size.height * 0.5, right: size.width * 0.5)
            
            normalImage = normalImage?.resizableImage(withCapInsets: inset)
            selectedImage = selectedImage?.resizableImage(withCapInsets: inset)
            
            button.setBackgroundImage(normalImage, for: .normal)
            button.setBackgroundImage(selectedImage, for: .highlighted)
            button.setBackgroundImage(selectedImage, for: .selected)
            
            // 3.布局按钮
            button.frame = CGRect(x: CGFloat(i) * (bounds.width / CGFloat(manager.packages.count)), y: 0, width: (bounds.width / CGFloat(manager.packages.count)), height: bounds.height)
            
            // 4.添加按钮
            addSubview(button)
        }
    }
}
